package com.ops.chirpit;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;



import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class FriendActivity extends Activity{
	static final String TAG = "LocationHelper";
	public static String query = "";
	static JSONArray friendList = new JSONArray();
	ProgressThread progressThread;
	static ProgressDialog progressDialog;
	@Override
	public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.search_view);
      if(friendList.length()==0){
	      getFriends();
      }
      if(friendList.length()==0)
	      showDialog(ChirpItActivity.FRIENDS);
      buildPage(friendList);      
	}
	
	public void getFriends(){
		String FILENAME = "friend_list";  	
	      FileInputStream fis;
	      byte[] buffer;
		try {
			fis = openFileInput(FILENAME);
			buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			String string = new String(buffer);
			friendList = new JSONArray(string);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	protected Dialog onCreateDialog(int id) {
	  	String title = "";
	      switch(id) {
	      case ChirpItActivity.FRIENDS:
	      	title = "Friends";
	      	break;
	      default:
	      	return null;
	      }
	      progressDialog = new ProgressDialog(FriendActivity.this);
	      progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	      progressDialog.setMessage("Loading " + title + "...");
	      Message msg = Message.obtain();
	      msg.arg1 = 0; msg.arg2 = 0;msg.setTarget(handler);
	      progressDialog.setCancelMessage(msg);
	      return progressDialog;
	  }

	  @Override
	  protected void onPrepareDialog(int id, Dialog dialog) {
	      progressDialog.setProgress(0);
	      progressThread = new ProgressThread(handler, id);
	      progressThread.start();
	  }
	  // Define the Handler that receives messages from the thread and update the progress
	  final Handler handler = new Handler() {
	      public void handleMessage(Message msg) {
	    	  if (msg.arg1 < 0){
		        	Intent intent = new Intent(FriendActivity.this, ChirpItActivity.class);
		        	intent.putExtra("RESULT", "EXTRAS");
		        	setResult(RESULT_OK, intent);
		        	finish();
	    	  }
	          int total = msg.arg1, max = msg.arg2;
	          friendList = (JSONArray) msg.obj;
	          progressDialog.setMax(max);
	          progressDialog.setProgress(total);
	          if (total >= max){
	              dismissDialog(ChirpItActivity.FRIENDS);
	              ((ProgressThread) progressThread).setState(ProgressThread.STATE_DONE);
	              buildPage(friendList);

	              String FILENAME = "friend_list";
	              String string = friendList.toString();
	
	              FileOutputStream fos;
				try {
					fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
					fos.write(string.getBytes());
					fos.close();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	          }
	      }
	  };
	  
	  public void buildPage(JSONArray friendList){
		    if(friendList != null){
		        final ListView lv1 = (ListView)findViewById(R.id.listView1_ref);
		        final Button searchButton = (Button)findViewById(R.id.placeSearchButton);
		        final Button doneButton = (Button)findViewById(R.id.placesDoneButton);
		        final TextView searchText = (TextView)findViewById(R.id.textSearch);
		        
		        searchButton.setOnClickListener(new OnClickListener() {
		        	public void onClick(View arg0){
		        	    try {query = searchText.getText().toString();
							if(FriendActivity.query != ""){
								JSONArray filteredList = new JSONArray();
								for (int i = 0; i < FriendActivity.friendList.length();i++){
										if (FriendActivity.friendList.getJSONObject(i).getString("name").toLowerCase().contains(FriendActivity.query.toLowerCase())){
											filteredList.put(FriendActivity.friendList.getJSONObject(i));
										}
								}
								buildPage(filteredList);
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}	        	    
		        	}
		        });
		  	    doneButton.setOnClickListener(new OnClickListener() {
			        public void onClick(View arg0){
			        	Intent intent = new Intent(FriendActivity.this, ChirpItActivity.class);
			        	intent.putExtra("RESULT", "EXTRAS");
			        	setResult(RESULT_OK, intent);
			        	finish();
			        }
		  	    });
		        lv1.setAdapter(new CustomBaseAdapter(this, friendList, ChirpItActivity.FRIENDS));
		      	lv1.setOnItemClickListener(new OnItemClickListener() {
		      		//@Override
		      		public void onItemClick(AdapterView<?> arg0, View view,
		                int position, long id) {
		            // do whatever you want here
		              Object o = lv1.getItemAtPosition(position);
		              JSONObject fullObject = (JSONObject)o;
		              try {
		            	ChirpItActivity.attachFriends[fullObject.getInt("provider")].put(fullObject);
						Toast.makeText(FriendActivity.this, "You have chosen: " + " " + fullObject.getString("name"), Toast.LENGTH_LONG).show();
		              } catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						Log.e(TAG,e.getMessage());
		              }
		      		}
		      	});
		    }
	  }
}
